﻿using System;
using System.Web;
using System.Web.Services;
using System.Web.Script.Services;
using UDS.Components;
using System.Web.Security;

namespace UDS.WebApp
{
    /// <summary>
    /// This service will serve as an AJAX service in online.aspx page.
    /// </summary>
    [WebService(Namespace = "http://www.chzhou.com/uds/online_service")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [ScriptService]
    public class OnlineService : WebService
    {
        [Serializable]
        public class CheckUpdateResult
        {
            public int NumOnlineUsers
            {
                get;
                set;
            }

            public bool HasNewMessage
            {
                get;
                set;
            }
        }

        [WebMethod]
        public CheckUpdateResult CheckUpdate()
        {
            return CheckUpdateInternal(HttpContext.Current);
        }

        internal static CheckUpdateResult CheckUpdateInternal(HttpContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            /*
             * 1. 更新activetime 
             * 2. 判断sessionid 
             * 3. 删除十分钟内未活动人 
             * 4. 拿到最新在线人数
             */

            // numUsers -1 是指非法登陆
            int nodeId = SiteContext.Current.ActiveNodeID;
            int numUsers;
            var siteContext = SiteContext.Current;
            bool hasNewMsg = SMS.CheckUpdate(siteContext.UserName, siteContext.SessionID.ToString(), nodeId, out numUsers);

            CheckUpdateResult result = new CheckUpdateResult();
            result.NumOnlineUsers = numUsers;
            result.HasNewMessage = hasNewMsg;
            if (result.NumOnlineUsers == -1)
            {
                // The user's account was used on more than one computer.
                // Therefore, we disable the current logon.
                if (!UDSConfig.AllowMultipleLogon)
                {
                    // clear everything
                    FormsAuthentication.SignOut();
                    context.Request.Cookies.Clear();

                    context.Session.Clear();
                }
            }

            return result;
        }
    }
}
